class AsyncTaskController {
  maxConcurrent: number;
  taskQueue: Promise<any>[];
  currentConCurrent: number;
  constructor(maxConcurrent: number) {
    this.maxConcurrent = maxConcurrent;
    this.taskQueue = [];
    this.currentConCurrent = 0;
  }

  addTask(task: Promise<any>) {
    this.taskQueue.push(task);

    this.next();
  }

  next() {
    if (
      this.currentConCurrent < this.maxConcurrent &&
      this.taskQueue.length > 0
    ) {
      console.log(this.taskQueue, this.currentConCurrent);

      this.currentConCurrent++;
      const task = this.taskQueue.shift();
      if (!task) {
        return false;
      }
      task
        .then((result: any) => {
          console.log(result);
        })
        .catch((err: any) => {
          console.log(err);
        })
        .finally(() => {
          this.currentConCurrent--;
          this.next();
        });
    }
  }
}

export default AsyncTaskController;
